import { Button, Progress, Table, Upload } from 'antd'
import { useAtom, useAtomValue } from 'jotai'
import { myPeerIdAtom, peersAtom } from '@/atom'
import { getNameFromId, sendDataToPeers } from '@/utils/peer'
import { filesAtom } from './atom'
import { createFileWritable, getFilesRecursively } from './util'
import { notification } from '../Layout/Layout'

// 格式化文件大小的工具函数
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化下载速度的工具函数
const formatSpeed = (bytesPerSecond: number): string => {
  if (bytesPerSecond === 0) return '0 B/s'
  const k = 1024
  const sizes = ['B/s', 'KB/s', 'MB/s', 'GB/s']
  const i = Math.floor(Math.log(bytesPerSecond) / Math.log(k))
  return parseFloat((bytesPerSecond / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化时长的工具函数
const formatDuration = (milliseconds: number): string => {
  const seconds = Math.floor(milliseconds / 1000)
  const minutes = Math.floor(seconds / 60)
  const hours = Math.floor(minutes / 60)
  
  if (hours > 0) {
    return `${hours}h${minutes % 60}m${seconds % 60}s`
  } else if (minutes > 0) {
    return `${minutes}m${seconds % 60}s`
  } else {
    return `${seconds}s`
  }
}

const File: React.FC = () => {
  const [files, setFiles] = useAtom(filesAtom)
  const peers = useAtomValue(peersAtom)
  const myPeerId = useAtomValue(myPeerIdAtom)

  return (
    <div
      style={{
        width: '100dvw',
        height: 'calc(100dvh - 50px)',
        boxSizing: 'border-box',
        overflow: 'auto',
        position: 'relative',
      }}
    >
      <div
        style={{
          display: 'flex',
          padding: 8,
          gap: 8,
          justifyContent: 'flex-end',
        }}
      >
        {(window as any).showOpenFilePicker ? (
          <Button
            type="primary"
            onClick={async () => {
              const [fileHandle] = await (window as any).showOpenFilePicker()
              const file = {
                id: crypto.randomUUID(),
                name: fileHandle.name,
                type: fileHandle.kind,
                fileHandle,
                user: getNameFromId(myPeerId),
                peerId: myPeerId,
              }
              setFiles((o) => [...o, file])
              sendDataToPeers({
                type: 'file-add',
                data: { ...file, fileHandle: undefined },
              })
            }}
          >
            文件
          </Button>
        ) : (
          <Upload
            customRequest={({ file }: any) => {
              const fileData = {
                id: crypto.randomUUID(),
                name: file.name,
                type: 'file',
                file,
                contentType: file.type,
                user: getNameFromId(myPeerId),
                peerId: myPeerId,
              }
              setFiles((o) => [...o, fileData])
              sendDataToPeers({
                type: 'file-add',
                data: { ...fileData, file: undefined },
              })
            }}
            showUploadList={false}
          >
            <Button type="primary">文件</Button>
          </Upload>
        )}
        <Button
          type="primary"
          onClick={async () => {
            const dirHandle = await (window as any).showDirectoryPicker()
            const fileHandles = await getFilesRecursively(dirHandle)
            if (fileHandles.length) {
              const subFiles = []
              for await (const fileHandle of fileHandles) {
                const relativePaths = await dirHandle.resolve(fileHandle)
                subFiles.push({
                  id: crypto.randomUUID(),
                  name: fileHandle.name,
                  fileHandle,
                  relativePaths: relativePaths.slice(0, -1),
                })
              }
              const file = {
                id: crypto.randomUUID(),
                name: dirHandle.name,
                type: dirHandle.kind,
                dirHandle,
                subFiles,
                user: getNameFromId(myPeerId),
                peerId: myPeerId,
              }
              setFiles((o) => [...o, file])
              sendDataToPeers({
                type: 'file-add',
                data: {
                  ...file,
                  dirHandle: undefined,
                  subFiles: file.subFiles.map((f) => ({
                    ...f,
                    fileHandle: undefined,
                  })),
                },
              })
            } else {
              notification.error({ message: '该文件夹下没有文件' })
            }
          }}
        >
          文件夹
        </Button>
      </div>
      <Table
        rowKey="id"
        columns={[
          {
            title: 'Name',
            dataIndex: 'name',
          },
          {
            title: 'Type',
            dataIndex: 'type',
          },
          //   {
          //     title: "Size",
          //     dataIndex: "size",
          //   },
          {
            title: 'User',
            dataIndex: 'user',
          },
          {
            title: 'Operate',
            width: 300,
            render: (record: any) => (
              <div>
                {record.peerId === myPeerId && (
                  <Button
                    danger
                    type="link"
                    onClick={async () => {
                      setFiles((o) => o.filter((i) => i.id !== record.id))
                      sendDataToPeers({
                        type: 'file-remove',
                        data: record.id,
                      })
                    }}
                  >
                    移除
                  </Button>
                )}
                {record.peerId !== myPeerId &&
                  !record.downloading &&
                  record.type === 'file' && (
                    <Button
                      type="link"
                      onClick={async () => {
                        const peer = peers.find(
                          (p) => p.peerId === record.peerId,
                        )
                        if (peer) {
                          if ((window as any).showSaveFilePicker) {
                            const fileHandle = await (
                              window as any
                            ).showSaveFilePicker({ suggestedName: record.name })
                            const writable = await fileHandle.createWritable()
                            setFiles((o) =>
                              o.map((f) => {
                                if (f.id === record.id) {
                                  return { ...f, writable }
                                }
                                return f
                              }),
                            )
                          }
                          peer.conn?.send({
                            type: 'request-download',
                            data: record.id,
                          })
                          // } else {
                          //   peer.conn?.send({
                          //     type: 'request-download-legacy',
                          //     data: record.id,
                          //   })
                          // }
                        } else {
                          notification.error({
                            message: '该文件发送人已离线',
                          })
                          sendDataToPeers({
                            type: 'file-remove',
                            data: record.id,
                          })
                        }
                      }}
                    >
                      下载
                    </Button>
                  )}
                {record.peerId !== myPeerId &&
                  !record.downloading &&
                  record.type === 'directory' && (
                    <Button
                      type="link"
                      onClick={async () => {
                        const peer = peers.find(
                          (p) => p.peerId === record.peerId,
                        )
                        if (peer) {
                          const dirHandle = await (
                            window as any
                          ).showDirectoryPicker()
                          for await (const subFile of record.subFiles) {
                            const writable = await createFileWritable(
                              dirHandle,
                              subFile.name,
                              subFile.relativePaths,
                            )
                            subFile.writable = writable
                          }
                          setFiles((o) =>
                            o.map((f) => {
                              if (f.id === record.id) {
                                return {
                                  ...f,
                                  dirHandle,
                                  subFiles: record.subFiles,
                                }
                              }
                              return f
                            }),
                          )
                          peer.conn?.send({
                            type: 'request-download',
                            data: record.id,
                          })
                        } else {
                          notification.error({ message: '该文件发送人已离线' })
                          sendDataToPeers({
                            type: 'file-remove',
                            data: record.id,
                          })
                        }
                      }}
                    >
                      下载
                    </Button>
                  )}
                {record.downloading && record.type === 'file' && (
                  <div>
                    <Progress
                      percent={record.downloading.percentage || 0}
                      status={
                        record.downloading.percentage === 100
                          ? 'success'
                          : 'active'
                      }
                    />
                    <div style={{ fontSize: '12px', color: '#666', marginTop: '4px' }}>
                      <div>
                        {formatFileSize(record.downloading.receivedSize || 0)} / {formatFileSize(record.downloading.totalSize || 0)}
                        {record.downloading.speed > 0 && (
                          <span style={{ marginLeft: '8px' }}>
                            {formatSpeed(record.downloading.speed)}
                          </span>
                        )}
                      </div>
                      {record.downloading.isCompleted && record.downloading.duration > 0 && (
                        <div style={{ color: '#52c41a', marginTop: '2px' }}>
                          下载完成，总耗时: {formatDuration(record.downloading.duration)}
                        </div>
                      )}
                      {!record.downloading.isCompleted && record.downloading.startTime && (
                        <div style={{ color: '#1890ff', marginTop: '2px' }}>
                          已用时: {formatDuration(Date.now() - record.downloading.startTime)}
                        </div>
                      )}
                    </div>
                  </div>
                )}
                {record.downloading && record.type === 'directory' && (
                  <div>
                    {record.subFiles.map((subFile: any) => (
                      <div key={subFile.id} style={{ marginBottom: '8px' }}>
                        <div style={{ fontSize: '12px', marginBottom: '4px' }}>
                          {subFile.relativePaths.length
                            ? '/' + subFile.relativePaths.join('/')
                            : ''}
                          /{subFile.name}
                        </div>
                        <Progress
                          percent={subFile.percentage || 0}
                          status={
                            subFile.percentage === 100
                              ? 'success'
                              : 'active'
                          }
                        />
                        <div style={{ fontSize: '10px', color: '#666', marginTop: '2px' }}>
                          <div>
                            {formatFileSize(subFile.receivedSize || 0)} / {formatFileSize(subFile.totalSize || 0)}
                            {subFile.speed > 0 && (
                              <span style={{ marginLeft: '8px' }}>
                                {formatSpeed(subFile.speed)}
                              </span>
                            )}
                          </div>
                          {subFile.isCompleted && subFile.duration > 0 && (
                            <div style={{ color: '#52c41a', marginTop: '1px' }}>
                              完成，耗时: {formatDuration(subFile.duration)}
                            </div>
                          )}
                          {!subFile.isCompleted && subFile.startTime && (
                            <div style={{ color: '#1890ff', marginTop: '1px' }}>
                              已用时: {formatDuration(Date.now() - subFile.startTime)}
                            </div>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            ),
          },
        ]}
        dataSource={files}
      />
    </div>
  )
}

export default File
